const Category = require('../models/category.model')
const { Sequelize } = require('sequelize');
class CategoryService {
    // 模糊查询接口
    async searchCategorylist({ category_name, pageNum, pageSize }) {
        const offset = (pageNum - 1) * pageSize;
        try {
            // 统计一级分类的数量（满足模糊搜索条件的）
            const total = await Category.count({
                where: {
                    parent_category_id: 0,
                    category_name: { [Sequelize.Op.like]: `%${category_name}%` },
                },
            });

            // 查询满足条件的一级分类，并包含子分类
            const rows = await Category.findAll({
                where: {
                    parent_category_id: 0, // 只查一级分类
                    category_name: { [Sequelize.Op.like]: `%${category_name}%` },
                },
                attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                offset: offset,
                limit: pageSize,
                include: [
                    {
                        attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                        model: Category,
                        as: 'children', // 二级分类
                        required: false,
                        include: [
                            {
                                attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                                model: Category,
                                as: 'children', // 三级分类
                                required: false,
                            },
                        ],
                    },
                ],
            });

            return {
                pageNum,
                pageSize,
                total, // 只返回符合搜索条件的一级分类总数
                list: rows,
            };
        } catch (error) {
            throw new Error(error.message);
        }
    }

    async createCategory(data) {
        const { category_name, parent_category_id, status } = data
        try {
            const category = await Category.create({
                category_name,
                parent_category_id,
                status
            })
            return category
        } catch (error) {
            throw new Error(error)
        }
    }
    async removeCategory(id) {
        try {
            const res = await Category.destroy({ where: { id } })
            return res > 0 ? true : false
        } catch (error) {
            throw new Error(error)
        }
    }

    async getCategoryChildById(id) {
        try {
            const category = await Category.findOne({
                where: { parent_category_id: id },
            })
            return category
        } catch (error) {
            throw new Error(error)
        }
    }

    async getCategoryfatherById(id) {
        try {
            const category = await Category.findOne({
                where: { id: id },
            })
            return category
        } catch (error) {
            throw new Error(error)
        }
    }

    async update(id, date) {
        try {
            return await Category.update(date, {
                where: { id: id }
            })
        } catch (error) {
            throw new Error(error)
        }
    }

    async getCategoryById(id) {
        try {
            return await Category.findOne({
                where: { id: id }
            })
        } catch (error) {
            throw new Error(error)
        }
    }

    async getCategoryList(pageNum, pageSize) {
        const offset = (pageNum - 1) * pageSize
        try {
            const total = await Category.count({ where: { parent_category_id: 0 } });
            const { rows } = await Category.findAndCountAll({
                attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                offset: offset,
                limit: pageSize * 1,
                where: { parent_category_id: 0 }, // 查询一级分类
                include: [
                    {
                        attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                        model: Category,
                        as: 'children', // 二级分类
                        required: false, // 即使没有子分类也返回一级分类
                        include: [
                            {
                                attributes: ['id', 'category_name', 'parent_category_id', 'status'],
                                model: Category,
                                as: 'children', // 三级分类
                                required: false,
                            }
                        ]
                    }
                ]
            });

            return {
                pageNum,
                pageSize,
                total: total,
                list: rows,

            }
        } catch (error) {
            console.error('获取分类列表失败:', error);
            throw error;
        }
    }


    async checkCategoryBycategory_name(category_name) {
        try {
            return await Category.findOne({
                where: { category_name: category_name }
            })
        } catch (error) {
            throw new Error(error)
        }
    }
}

module.exports = new CategoryService()